const express = require('express')
const router = express.Router()
const User = require('../db/model/userModel')
const {send} = require('process')
const sendMail = require('../utils/mail')

//注册
router.post('/reg',(req,res)=>{
    let {mail,pwd,nickname,verifyCode} = req.body
    if(mail && pwd && nickname && verifyCode){
        if(codes[mail].code != verifyCode){
            return res.send({err:-4,msg:"验证码错误"})
        }
        User.find({mail}).then(data=>{
            if(data.length === 0){
                return User.insertMany({mail,pwd,nickname})
            }else{
                res.send({err:-3,msg:"邮箱已注册"})
            }
        }).then(()=>{
            res.send({err:0,msg:"注册成功"})
        }).catch(err=>{
            console.log(err)
            res.send({err:-2,msg:"系统错误"})
        })
    }else{
        res.send({err:-1,msg:'参数错误'})
    }
})
//登录
router.post('/login',(req,res)=>{
    let {mail,pwd} = req.body
    if(!mail || !pwd) return res.send({err:-1,msg:"参数错误"})
    User.find({mail,pwd}).then(data=>{
        if(data.length > 0){
            res.send({err:0,msg:"登录成功",data:data[0]})
        }else{
            res.send({err:-1,msg:"邮箱或密码不正确"})
        }
    }).catch(err=>{
        res.send({err:-2,msg:"系统错误"})
    })
})
//发送验证码
let codes = {} //将验证码保存在内存中
router.post('/sendcode',(req,res)=>{
    let {mail} = req.body
    if(codes[mail]){
        if(new Date().getTime() - codes[mail].time < 60000){
            res.send({err:-2,msg:"操作过于频繁"})
        }
    }
    let code = parseInt(Math.random()*10000)  //产生随机验证码
    sendMail.send(mail,code).then(()=>{
        codes[mail] = {code,time:new Date().getTime()}
        res.send({err:0,msg:"验证码发送成功"})
    }).catch(err=>{
        res.send({err:-1,msg:"发送失败"})
    })
})
//根据id查询
router.post('/whoami',(req,res)=>{
    let {_id} = req.body
    if(_id){
        User.find({_id}).then(data=>{
            if(data.length > 0){
                res.send({err:0,msg:"ok",data:data[0]})
            }else{
                console.log("用户不存在");
                return res.send({err:-1,msg:"该用户不存在"})
            }
        }).catch(err=>{
            console.log(err);
            return res.send({err:-2,msg:"系统错误"})
        })
    }else{
        res.send({err:-3,msg:"参数错误"})
    }
})

module.exports = router